
import json
import os
import subprocess
import time
# coding=utf-8
# 下载文件需要的lib
import urllib.request
# 时间转换模块
from datetime import datetime

from selenium import webdriver
from selenium.common.exceptions import TimeoutException  # 导入所有的异常类
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait

import settings


def chromeOptions(noWin=False, noImg=False, pdf=False):
    # 设置 chrome_options 属性
    chrome_options = webdriver.ChromeOptions()
    # 设置浏览器窗口大小
    chrome_options.add_argument('window-size=1800x2000')
    # 无界面
    chrome_options.add_argument('--headless') if noWin else ""
    # 不加载图片
    chrome_options.add_argument('blink-settings=imagesEnabled=false') if noImg else ""
    # 设置代理
    # self.chrome_options.add_argument('--proxy-server=http://127.0.0.1:1080')

    # for linux/*nix, download_dir="/usr/Public"
    download_dir = os.path.join(settings.BASEDIR, 'files')
    # ----------页面打印版pdf下载-----------------
    appState = {
        "recentDestinations": [
            {
                "id": "Save as PDF",
                "origin": "local"
            }
        ],
        "selectedDestinationId": "Save as PDF",
        "version": 2
    }
    # ----------网页版pdf直接下载-----------------
    profile = {
        "plugins.plugins_list": [{
            "enabled": False, "name": "Chrome PDF Viewer"
        }],  # Disable Chrome's PDF Viewer
        "download.default_directory": download_dir,
        "download.extensions_to_open": "applications/pdf",
        'printing.print_preview_sticky_settings.appState': json.dumps(appState),
        'savefile.default_directory': download_dir
    }
    chrome_options.add_experimental_option("prefs", profile) if pdf else ""
    return chrome_options


class Tools():

    logger = settings.get_log("Tools")
    # 初始化
    # def __init__(self):
    #     self.Datetools = Datetools();
    # pass;

    # 上传文件专用转义
    def repr(self, text):
        self.logger.info('*****************')
        path = repr(text)
        self.logger.info('path1: %s' % path)
        num = path.find('u', 0, 1)
        if num == 0:
            path = path[2:len(path) - 1]
        else:
            path = path[1:len(path) - 1]
        pass
        self.logger.info('path2: %s' % path)
        path = os.path.normcase(path)
        self.logger.info('path3: %s' % path)
        self.logger.info('*****************')
        return path
    pass

    def cmd_run(self, str_list):
        cmd_str = ' '.join(str_list)
        p = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE)
        p.wait()
        cmd_res = p.stdout.read()
        if p.returncode == 0:
            return cmd_res
        else:
            return str(p.returncode)
    pass

    def is_empty(self, obj):
        if obj is None:
            return True
        pass
        if obj == 'None':
            return True
        pass
        if str(obj).strip() == '':
            return True
        pass
        return False
    pass

    def obj_to_json(self, obj):
        if self.is_empty(obj):
            return ''
        pass
        return json.dumps(obj)
    pass

    def get_obj2str(self, obj):
        if obj is None:
            return ''
        pass
        if str(obj).strip() == '':
            return ''
        pass
        return str(obj)
    pass

    def get_day(self, dateStr, splitstr='-'):
        '''dateStr 2017-07-06'''
        if dateStr is None:
            return ''
        return str(int(str(dateStr.split(splitstr)[2])))
        pass

    def get_month(self, dateStr, splitstr='-'):
        '''dateStr 2017-07-06'''
        if dateStr is None:
            return ''
        return str(int(str(dateStr.split(splitstr)[1])))
        pass

    def get_year(self, dateStr, splitstr='-'):
        '''dateStr 2017-07-06'''
        if dateStr is None:
            return ''
        return str(int(str(dateStr.split(splitstr)[0])))
        pass

    def get_dayi(self, dateStr, splitstr='-'):
        '''dateStr 2017-07-06'''
        if dateStr is None:
            return ''
        return int(str(dateStr.split(splitstr)[2]))
        pass

    def get_monthi(self, dateStr, splitstr='-'):
        '''dateStr 2017-07-06'''
        if dateStr is None:
            return ''
        return int(str(dateStr.split(splitstr)[1]))
        pass

    def get_yeari(self, dateStr, splitstr='-'):
        '''dateStr 2017-07-06'''
        if dateStr is None:
            return ''
        return int(str(dateStr.split(splitstr)[0]))
        pass

    def get_dday(self, date, splitstr='-'):
        if self.is_empty(date):
            return ''
        pass
        dateStr = Datetools().date_to_str(date)
        return str(int(str(dateStr.split(splitstr)[2])))
        pass
    pass

    def get_dmonth(self, date, splitstr='-'):
        if self.is_empty(date):
            return ''
        pass
        dateStr = Datetools().date_to_str(date)
        return str(int(str(dateStr.split(splitstr)[1])) - 1)
        pass
    pass

    def get_dyear(self, date, splitstr='-'):
        if self.is_empty(date):
            return ''
        pass
        dateStr = Datetools().date_to_str(date)
        return str(int(str(dateStr.split(splitstr)[0])))
        pass
    pass

    def get_ddayi(self, date, splitstr='-'):
        if self.is_empty(date):
            return ''
        pass
        dateStr = Datetools().date_to_str(date)
        return int(str(dateStr.split(splitstr)[2]))
        pass
    pass

    def get_dmonthi(self, date, splitstr='-'):
        if self.is_empty(date):
            return ''
        pass
        dateStr = Datetools().date_to_str(date)
        return int(str(dateStr.split(splitstr)[1]))
        pass
    pass

    def get_dyeari(self, date, splitstr='-'):
        if self.is_empty(date):
            return ''
        pass
        dateStr = Datetools().date_to_str(date)
        return int(str(dateStr.split(splitstr)[0]))
        pass
    pass

    def convertFinancialTypeForAustralia(self, financialType):
        financialTypeDict = {}
        financialTypeDict['0'] = '1'  # 自费
        financialTypeDict['1'] = '2'  # 其他人
        financialTypeDict['3'] = '3'  # 其他组织
        financialTypeDict['4'] = '4'  # 海外雇主
        return financialTypeDict[str(financialType)]
        pass

    def convertProvinceForAustralia(self, province):
        if self.is_empty(province):
            return ''
        if province == 'XIZANG':
            province = 'XIZANG ZIZHIQU'
        elif province == 'GUANGXI':
            province = 'GUANGXI ZHUANGZU ZIZHIQU'
        elif province == 'InnerMongolia':
            province = 'NEI MONGOL ZIZHIQU'
        elif province == 'NINGXIA':
            province = 'NINGXIA HUIZI ZIZHIQU'
        elif province == 'XINJIANG':
            province = 'XINJIANG UYGUR ZIZHIQU'
        elif province == 'SHANGHAI' or province == 'BEIJING' or province == 'TIANJIN' or province == 'CHONGQING':
            province = province + ' SHI'
        else:
            province = province + ' SHENG'
        return province
        pass

    def convertRelationshipStatusForAustralia(self, relationshipStatus):
        if self.is_empty(relationshipStatus):
            return ''
        if relationshipStatus == '10301':
            relationshipStatus = 'M'
        elif relationshipStatus == '10302':
            relationshipStatus = 'N'
        elif relationshipStatus == '10303':
            relationshipStatus = 'D'
        elif relationshipStatus == '10304':
            relationshipStatus = 'W'
        return relationshipStatus
        pass

    def convertDateForAustralia(self, dateStr, splitstr='-'):
        '''dateStr 2017-07-06'''
        if self.is_empty(dateStr):
            return ''
        year = str(dateStr.split(splitstr)[0])
        month = str(dateStr.split(splitstr)[1])
        day = str(dateStr.split(splitstr)[2])
        if month == '01':
            month = 'Jan'
        elif month == '02':
            month = 'Feb'
        elif month == '03':
            month = 'Mar'
        elif month == '04':
            month = 'Apr'
        elif month == '05':
            month = 'May'
        elif month == '06':
            month = 'Jun'
        elif month == '07':
            month = 'Jul'
        elif month == '08':
            month = 'Aug'
        elif month == '09':
            month = 'Sep'
        elif month == '10':
            month = 'Oct'
        elif month == '11':
            month = 'Nov'
        elif month == '12':
            month = 'Dec'
        return day + ' ' + month + ' ' + year
        pass

    def convertFamilyRelationForAustralia(self, relation):
        familyRelation = {}
        familyRelation['10101'] = '62'  # 父亲
        familyRelation['10102'] = '62'  # 母亲
        familyRelation['10103'] = '3'  # 配偶
        familyRelation['1120102'] = '36'  # 姐妹
        familyRelation['1120101'] = '35'  # 兄弟
        familyRelation['138002001'] = '1'  # 子女
        familyRelation['138002002'] = '1'  # 子女
        familyRelation['1120105'] = '39'  # 姑妈/伯母/姨妈
        familyRelation['1120106'] = '39'  # 叔叔/舅舅/姑父
        familyRelation['1120107'] = '31'  # 表姐妹/表兄弟
        familyRelation['1120108'] = '42'  # 外甥/侄
        familyRelation['1120109'] = '41'  # 外甥女/侄女
        familyRelation['1120110'] = '18'  # 爷爷
        familyRelation['1120111'] = '18'  # 奶奶
        familyRelation['1120112'] = '18'  # 姥爷，姥姥
        familyRelation['1120114'] = '11'  # 朋友
        familyRelation['1120115'] = '11'  # 同事
        return familyRelation[str(relation)]
    pass

    def convertExtraRelationForAustralia(self, relation):
        familyRelation = {}
        familyRelation['1120210'] = '62'  # 父亲
        familyRelation['1120211'] = '62'  # 母亲
        familyRelation['10103'] = '3'  # 配偶
        familyRelation['1120215'] = '36'  # 姐妹
        familyRelation['1120214'] = '35'  # 兄弟
        familyRelation['1120212'] = '1'  # 子女
        familyRelation['1120213'] = '1'  # 子女
        familyRelation['1120201'] = '39'  # 姑妈/伯母/姨妈
        familyRelation['1120202'] = '39'  # 叔叔/舅舅/姑父
        familyRelation['1120203'] = '31'  # 表姐妹/表兄弟
        familyRelation['1120204'] = '42'  # 外甥/侄
        familyRelation['1120205'] = '41'  # 外甥女/侄女
        familyRelation['1120206'] = '18'  # 爷爷
        familyRelation['1120207'] = '18'  # 奶奶
        familyRelation['1120208'] = '18'  # 姥爷，姥姥
        familyRelation['1120216'] = '11'  # 朋友
        familyRelation['1120217'] = '11'  # 同事
        return familyRelation[str(relation)]
    pass

    def get_dic_value(self, bean, key):
        ''' 获取字典的值，若不存在，返回空值 '''
        try:
            return bean[key]
        except Exception:
            return ''
        pass

    #########start 获取文件路径、文件名、后缀名############
    def jwkj_get_filePath_fileName_fileExt(self, filename):
        (filepath, tempfilename) = os.path.split(filename)
        (shotname, extension) = os.path.splitext(tempfilename)
        return filepath, shotname, extension
    pass
    #########start 获取文件路径、文件名、后缀名############
    # 下载输出百分比

    def Schedule(self, dbnum, dbsize, size):
        print_true = False
        '''''
        a:已经下载的数据块
        b:数据块的大小
        c:远程文件的大小
       '''
        per = 100.0 * dbnum * dbsize / size
        if per > 100:
            per = 100
        pass
        if per >= 20 and per < 21:
            print_true = True
        # elif per >= 40 and per < 41:
            # print_true = True;
        elif per >= 60 and per < 61:
            print_true = True
        # elif per >= 80 and per < 81:
            # print_true = True;
        elif per >= 100:
            print_true = True
        pass
        if print_true:
            print_info = 'appid={},[{}/{}][{}] === {:.2f}%'.format(
                self.app_id, self.now_down_index, self.count, self.filename, per
            )
            self.logger.info(print_info)
            # print_info = 'appid=' + str(self.app_id) + ',[' + str(self.now_down_index) + '/' + str(
            #     self.count) + '][' + self.filename + '] === ' + '%.2f%%' % per
        pass

    pass
    # 下载文件

    def down_file(self, url, local_path, app_id, now_down_index, count):
        # 检查目录是否存在,不存在就创建目录
        if not os.path.exists(local_path):
            os.makedirs(local_path)
        pass
        filepath, shotname, extension = self.jwkj_get_filePath_fileName_fileExt(url)
        self.app_id = app_id
        self.filename = shotname + extension
        self.local_path = local_path
        self.now_down_index = now_down_index
        self.count = count
        local = os.path.join(self.local_path, self.filename)
        urllib.request.urlretrieve(url, local, self.Schedule)
    pass


class Huilian(object):
    """基亍原生的 selenium 框架做了二次封装."""

    logger = settings.get_log("hulian")

    def __init__(self, driver):
        """启劢浏览器参数化，默认启劢 firefox."""
        if driver:
            self.driver = driver
        else:
            chrome_path = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver"
            self.driver = webdriver.Chrome(executable_path=chrome_path)

    def open(self, url, t='', timeout=10):
        '''
        使用 get 打开 url 后，最大化窗口，刞断 title 符合预期
        Usage:
        driver = Huilian()
        driver.open(url,t='')
        '''
        if url != '-1':
            self.driver.get(url)
        self.driver.maximize_window()
        try:
            WebDriverWait(self.driver, timeout).until(EC.title_contains(t))
        except TimeoutException:
            self.logger.debug("open %s title error" % url)
        except Exception as msg:
            self.logger.debug("Error:%s" % msg)
        pass

    @property
    def page(self):
        """ 返回网页源码 """
        return self.driver.page_source

    # 判断元素是否存在
    def is_element_exist(self, locator):
        try:
            s = self.find_element(locator, 3)
            return True
        except TimeoutException as e:
            self.logger.debug('未找到按钮...')
            return False
        pass
    pass

    def find_element_by_id(self, id):
        return self.driver.find_element_by_id(id)
        pass

    def find_element(self, locator, timeout=30, type=1):
        '''定位元素，参数
        locator 是元祖类型
        Usage:locator = ("id","xxx")
        driver.find_element(locator)
        CLASS_NAME = 'class name'
        CSS_SELECTOR = 'css selector'
        ID = 'id'
        LINK_TEXT = 'link text'
        NAME = 'name'
        PARTIAL_LINK_TEXT = 'partial link text'
        TAG_NAME = 'tag name'
        XPATH = 'xpath
        '''

        # self.logger.info(( 'locators:'+str(locators) ))
        # element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(*locator))
        # element = WebDriverWait(self.driver, 20).until(lambda x: x.find_element(*locator))
        # element = WebDriverWait(driver,10).until(self.driver.find_element(by=By.ID,value='su'))
        if type == 1 or type == 2:
            element = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located(locator))
        elif type == 3:
            element = self.find_visibility_element(locator)
        pass
        # if locator[0] == "id" :
        #     elemet = self.driver.find_element_by_id(locator[1])
        # elif locator[0] == "name" :
        #     elemet = self.driver.find_element_by_name(locator[1])
        # elif locator[0] == "xpath" :
        #     elemet = self.driver.find_element_by_xpath(locator[1])
        # elif locator[0] == "css" :
        #     elemet = self.driver.find_element_by_css_selector(locator[1])
        # elif locator[0] == "class" :
        #     elemet = self.driver.find_element_by_class_name(locator[1])
        # elif locator[0] == "link" :
        #     elemet = self.driver.find_element_by_link_text(locator[1])
        # elif locator[0] == "partial_link" :
        #     elemet = self.driver.find_element_by_partial_link_text(locator[1])
        # elif locator[0] == "tag" :
        #     elemet = self.driver.find_element_by_tag_name(locator[1])
        return element

    # 等待并获取隐藏的元素
    def find_visibility_element(self, locator, timeout=60):
        '''等待并获取隐藏的元素
        定位元素，参数
        locator 是元组类型
        Usage:locator = ("id","xxx")
        driver.find_element(locator)
        CLASS_NAME = 'class name'
        CSS_SELECTOR = 'css selector'
        ID = 'id'
        LINK_TEXT = 'link text'
        NAME = 'name'
        PARTIAL_LINK_TEXT = 'partial link text'
        TAG_NAME = 'tag name'
        XPATH = 'xpath

        '''
        element = WebDriverWait(self.driver, 60).until(
            EC.visibility_of_element_located(locator))

        return element

    def find_elements(self, locator, timeout=10):
        '''定位一组元素'''
        try:
            elements = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_all_elements_located(locator))
        except TimeoutException:
            elements = []
        # if locator[0] == "id" :
        #     elemet = self.driver.find_elements_by_id(locator[1])
        # elif locator[0] == "name" :
        #     elemet = self.driver.find_elements_by_name(locator[1])
        # elif locator[0] == "xpath" :
        #     elemet = self.driver.find_elements_by_xpath(locator[1])
        # elif locator[0] == "css" :
        #     elemet = self.driver.find_elements_by_css_selector(locator[1])
        # elif locator[0] == "class" :
        #     elemet = self.driver.find_elements_by_class_name(locator[1])
        # elif locator[0] == "link" :
        #     elemet = self.driver.find_elements_by_link_text(locator[1])
        # elif locator[0] == "partial_link" :
        #     elemet = self.driver.find_elements_by_partial_link_text(locator[1])
        # elif locator[0] == "tag" :
        #     elemet = self.driver.find_elements_by_tag_name(locator[1])

        return elements

    def click(self, locator, type=1):
        '''点击操作
        Usage:locator = ('id','xxx')
        driver.click(locator)
        '''
        element = self.find_element(locator, 10)
        if type == 1:
            if str(locator[0]) == 'name':
                js = f'document.getElementsByName("{locator[1]}")[0].click()'
                self.js_execute(js)
            elif str(locator[0]) == 'id':
                js = f'document.getElementById("{locator[1]}").click()'
                self.js_execute(js)
            else:
                element.click()
        else:
            element.click()
        pass

    def e_click(self, locator):
        element = self.find_element(locator, 30)
        element.click()
    pass

    def visibility_click(self, locator):
        '''等待隐藏按钮出现后,点击操作
        '''
        element = self.find_element(locator, 30, 3)
        element.click()

    def double_click(self, locator):
        '''双击
        Usage:locator = ("id","xxx")
        driver.click(locator)
        '''
        element = self.find_element(locator)
        ActionChains(self.driver).double_click(element).perform()
        pass

    def context_click(self, locator):
        '''右键
        Usage:locator = ("id","xxx")
        driver.click(locator)
        '''
        element = self.find_element(locator)
        ActionChains(self.driver).context_click(element).perform()
        pass

    def elem_send_keys(self, element, text):
        """ 根据已有元素发送字符 """
        element.clear()
        element.send_keys(text)

    def send_keys(self, locator, text, type=1):
        '''
        type == 1 js 优先,type == 2是等待按钮,type == 3 是等待隐藏按钮
                        収送文本，清空后输入
        Usage:
        locator = ("id","xxx")
        driver.send_keys(locator, text)
        '''
        element = self.find_element(locator, 30, type)
        element.clear()
        element.send_keys(text)

    def is_text_in_element(self, locator, text, timeout=10):
        '''刞断文本在元素里,没定位刡元素迒回 False，定位刡迒回刞断结果布尔值result = driver.text_in_element(locator, text)'''
        try:
            result = WebDriverWait(self.driver, timeout).until(
                EC.text_to_be_present_in_element(locator, text))
        except TimeoutException:
            self.logger.debug("元素没定位刡：%s" % str(locator))
            return False
        else:
            return result
        pass

    def is_text_in_value(self, locator, value, timeout=10):
        ''' 刞断元素的 value 值，没定位刡元素迒回 false,定位刡迒回刞 断结果布尔值 result = driver.text_in_element(locator, text)'''
        try:
            result = WebDriverWait(self.driver, timeout).until(
                EC.text_to_be_present_in_element_value(locator, value))
        except TimeoutException:
            self.logger.debug("元素没定位刡：%s" % str(locator))
            return False
        else:
            return result
        pass

    def is_title(self, title, timeout=10):
        '''刞断 title 完全等亍'''
        result = WebDriverWait(self.driver, timeout).until(EC.title_is(title))
        return result

    def is_title_contains(self, title, timeout=10):
        '''刞断 title 包吨'''
        result = WebDriverWait(self.driver, timeout).until(
            EC.title_contains(title))
        return result

    def is_selected(self, locator, timeout=10):
        '''刞断元素被选中，迒回布尔值,'''
        result = WebDriverWait(self.driver, timeout).until(
            EC.element_located_to_be_selected(locator))
        return result

    def is_selected_be(self, locator, selected=True, timeout=10):
        '''刞断元素的状态，selected 是期望的参数 true/False 迒回布尔值'''
        result = WebDriverWait(self.driver, timeout).until(
            EC.element_located_selection_state_to_be(locator, selected))
        return result

    def is_alert_present(self, timeout=10):
        '''刞断页面是否有 alert，有迒回 alert(注意返里是迒回 alert,丌是 True)没有迒回 False'''
        result = WebDriverWait(self.driver, timeout).until(
            EC.alert_is_present())
        return result

    def is_visibility(self, locator, timeout=10):
        '''元素可见迒回本身，丌可见迒回 Fasle'''
        result = WebDriverWait(self.driver, timeout).until(
            EC.visibility_of_element_located(locator))
        return result

    def is_invisibility(self, locator, timeout=10):
        '''元素可见迒回本身，丌可见迒回 True，没找刡元素也迒回 True'''
        result = WebDriverWait(self.driver, timeout).until(
            EC.invisibility_of_element_located(locator))
        return result

    def is_clickable(self, locator, timeout=1):
        '''元素可以点击 is_enabled 迒回本身，丌可点击迒回 Fasle'''
        try:
            result = WebDriverWait(self.driver, timeout).until(
                EC.element_to_be_clickable(locator))
        except TimeoutException:
            result = False
        return result

    def is_clickable_time(self, locator, timeout=10):
        """
        在 timeout 秒内判断元素是否可以被选中
        """
        for _ in range(timeout * 10):
            if self.is_clickable(locator):
                return True
            time.sleep(0.1)
        return False

    def is_located(self, locator, timeout=10):
        '''刞断元素有没被定位刡（幵丌意味着可见），定位刡迒回 element,没定位刡迒回 False'''
        result = WebDriverWait(self.driver, timeout).until(
            EC.presence_of_element_located(locator))
        return result

    def move_to_element(self, locator):
        '''鼠标悬停操作
        Usage:
        locator = ("id","xxx")
        driver.move_to_element(locator)
        '''
        element = self.find_element(locator)
        ActionChains(self.driver).move_to_element(element).perform()

    def back(self):
        """
        Back to old window.
        Usage:driver.back()
        """
        self.driver.back()

    def forward(self):
        '''Forward to old window.Usage:driver.forward()'''
        self.driver.forward()

    def close(self):
        ''' Close the windows.  Usage: driver.close() '''
        self.driver.close()

    def quit(self):
        ''' Quit the driver and close all the windows.Usage:driver.quit()'''
        self.driver.quit()

    def get_title(self):
        '''获叏 title'''
        return self.driver.title

    def get_current_url(self):
        '''获叏 url'''
        return self.driver.current_url

    def get_text(self, locator):
        element = self.find_element(locator)
        return element.text

    def get_attribute(self, locator=None, element=None, name=None):
        '''获叏属性'''
        if locator:
            element = self.find_element(locator)
        return element.get_attribute(name)

    def js_execute(self, js):
        '''执行 js'''
        return self.driver.execute_script(js)

    def js_focus_element(self, locator):
        '''聚焦元素'''
        target = self.find_element(locator)
        self.driver.execute_script("arguments[0].scrollIntoView();", target)

    def js_scroll_top(self):
        '''滚劢刡顶部'''
        js = "window.scrollTo(0,0)"
        self.driver.execute_script(js)

    def js_scroll_end(self):
        '''滚劢刡底部'''
        js = "window.scrollTo(0,document.body.scrollHeight)"
        self.driver.execute_script(js)

    def select_by_index(self, locator, index, element=None):
        '''通过索引,index 是索引第几个，从 0 开始'''
        self.is_clickable_time(locator)
        element = self.find_element(locator)
        Select(element).select_by_index(index)

    def select_by_value(self, locator, value, element=None):
        '''通过 value 属性'''
        self.is_clickable_time(locator)
        element = self.find_element(locator)
        Select(element).select_by_value(value)

    def select_by_text(self, locator, text, element=None):
        '''通过文本值定位'''
        self.is_clickable_time(locator)
        element = self.find_element(locator)
        Select(element).select_by_visible_text(text)

    def select_by_text_60(self, locator, text, element=None):
        '''通过文本值定位'''
        self.is_clickable_time(locator)
        element = self.find_element(locator, 60)
        Select(element).select_by_visible_text(text)

    # 等待隐藏元素出现并选择
    def select_visibility_by_text(self, locator, text, element=None):
        """ 等待隐藏元素出现并选择
        通过文本值定位
        """
        self.is_clickable_time(locator)
        element = self.find_element(locator, 30, 3)
        Select(element).select_by_visible_text(text)

    def select_has_element(self, element, **kwargs):
        """  """
        ids = element.get_attribute("id")
        locator = ("id", ids)
        self.is_clickable_time(locator)
        if kwargs.get("index"):
            Select(element).select_by_index(kwargs.get("index"))
        elif kwargs.get("value"):
            Select(element).select_by_value(kwargs.get("value"))
        elif kwargs.get("text"):
            Select(element).select_by_text(kwargs.get("text"))
        elif kwargs.get("text_60"):
            Select(element).select_by_text_60(kwargs.get("text_60"))
        elif kwargs.get("visibility"):
            Select(element).select_by_visibility(kwargs.get("visibility"))

    def get_screenshot_as_file(self, savepath):
        '''通过文本值定位 "D:\\Program Files\\NM.bmp"'''
        self.driver.get_screenshot_as_file(savepath)
        pass

    def screenshot_as_png(self, locator, type=1):
        element = self.find_element(locator, 30, type)
        return element.screenshot_as_png()


class Datetools:
    '''时间格式化工具'''

    # 字符串转时间
    def str_to_date(self, datestr, format="%Y-%m-%d"):
        if datestr is None:
            return ""
        return datetime.strptime(datestr, format)

    # 当前时间
    def date_now(self, format='%Y-%m-%d %H:%M:%S'):
        '''获取当前时间   format="%Y-%m-%d %H:%M:%S %f" '''
        dt = datetime.now()
        return dt.strftime(format)

    # 时间转字符串
    def date_to_str(self, date, format="%Y-%m-%d"):
        if date is None:
            return ""
        return date.strftime(format)

    # 把datetime转成字符串
    def datetime_toString(self, dt, format="%Y-%m-%d %H:%M:%S"):
        return dt.strftime(format)

    # 把字符串转成datetime
    def string_toDatetime(self, string, format="%Y-%m-%d %H:%M:%S"):
        return datetime.strptime(string, format)

    # 把字符串转成时间戳形式
    def string_toTimestamp(self, strTime):
        return time.mktime(self.string_toDatetime(strTime).timetuple())

    # 把时间戳转成字符串形式
    def timestamp_toString(self, stamp, format="%Y-%m-%d %H:%M:%S"):
        return time.strftime(format, time.localtime(stamp))

    # 把datetime类型转外时间戳形式
    def datetime_toTimestamp(self, dateTim):
        return time.mktime(dateTim.timetuple())


if __name__ == "__main__":
    chrome_path = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver"
    driver = webdriver.Chrome(executable_path=chrome_path)
    driver.get_screenshot_as_file("D:\\NM.bmp")
    h = Huilian(driver)
    h.open("http://www.baidu.com")
    h.get_screenshot_as_file("D:\\NM.bmp")

    time.sleep(0.2)